<template>
  <div>
    <!-- 面包屑导航 -->
    <el-card>
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
    </el-card>

    <!-- 搜索框 -->
    <el-row>
      <el-col :span="6" class="sou">
        <el-input v-model="search" placeholder="请输入内容" class="input-with-select">
          <el-button @click="searchUser" slot="append" icon="el-icon-search"></el-button>
        </el-input>
      </el-col>
      <el-col :span="2" class="sou">
        <el-button @click="isShowAddUser=true" type="success" plain>添加用户</el-button>
      </el-col>
    </el-row>

    <!-- 表格 -->
    <el-table ref="singleTable" :data="userData" highlight-current-row style="width: 100%">
      <el-table-column type="index" width="50"></el-table-column>
      <el-table-column property="username" label="姓名" width="180"></el-table-column>
      <el-table-column property="email" label="邮箱" width="220"></el-table-column>
      <el-table-column property="mobile" label="电话" width="220"></el-table-column>

      <el-table-column label="用户状态" width="120">
        <!-- 循环时，想要获取循环到的数据，使用slot-scope属性获取 -->
        <template slot-scope="scope">
          <!-- el-ui提供了change事件，当状态改变时事件触发 -->
          <!-- 事件触发时，出入当前用户所有信息，获取id及状态 -->
          <el-switch
            @change="mg_change(scope.row)"
            v-model="scope.row.mg_state"
            active-color="#13ce66"
            inactive-color="#ff4949"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template slot-scope="scope">
          <!-- 修改用户弹窗事件  传入当前行的用户信息 -->
          <el-button
            @click="editUser(scope.row)"
            size="mini"
            type="primary"
            icon="el-icon-edit"
            circle
          ></el-button>

          <!-- 修改用户角色弹窗 -->
          <el-button
            @click="editRole(scope.row)"
            size="mini"
            type="success"
            icon="el-icon-check"
            circle
          ></el-button>
          <!-- 删除用户按钮 -->
          <el-button
            @click="delUser(scope.row.id)"
            size="mini"
            type="danger"
            icon="el-icon-delete"
            circle
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

      <!-- size-change 每页条数的改变
          current-change 页码的改变
       -->
     <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page-sizes="[1, 3, 5, 10]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>

    <!-- el-dialog是一个可操作的弹窗 -->
    <!-- visible 属性控制展示隐藏 -->
    <el-dialog title="添加用户" :visible="isShowAddUser">
      <el-form :model="addUser">
        <el-form-item label="用户名">
          <el-input v-model="addUser.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="addUser.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="addUser.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="addUser.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isShowAddUser=false">取 消</el-button>
        <el-button @click="addUserPost" type="primary">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改用户窗口 -->
    <el-dialog title="修改用户" :visible="isShowEditUser">
      <el-form :model="editUserData">
        <el-form-item label="用户名">
          <el-input :disabled="true" v-model="editUserData.username" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="邮箱">
          <el-input v-model="editUserData.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="editUserData.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isShowEditUser=false">取 消</el-button>
        <el-button @click="editUserPut" type="primary">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 分配用户角色弹窗 -->
    <el-dialog title="分配角色" :visible="isShowEditRole">
      <el-form :model="editRoleData">
        <el-form-item label="用户名">
          <el-input :disabled="true" v-model="editRoleData.username" autocomplete="off"></el-input>
        </el-form-item>

        <el-select v-model="value" placeholder="请选择">
          <el-option v-for="item in options" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
        </el-select>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isShowEditRole=false">取 消</el-button>
        <el-button @click="editRolePut" type="primary">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Axios from "axios";

export default {
  data() {
    return {
      // 分页数据
      total:'',
      pagesize:1,
      nu:1,

      userData: [], // 用户数据列表
      search: "", //搜索内容
      isShowAddUser: false, // 控制添加用户的窗口
      //   添加用户时使用
      addUser: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },

      // 修改用户使用信息
      isShowEditUser: false,
      editUserData: {
        username: "",
        email: "",
        mobile: ""
      },

      // 分配用户角色
      isShowEditRole: false,
      value: "",
      options: [],
      editRoleData: {}
    };
  },

  methods: {
    // 每页条数的改变
    handleSizeChange(size){
      this.pagesize = size;
      this.getusers();
    },

  // 页码的改变
    handleCurrentChange(nu){
      this.nu = nu;
      this.getusers()
    },

    // 获取用户列表信息，并复制渲染都表格
    getusers(query = "") {
      if (query == "") {
        var url = `users?pagenum=${this.nu}&pagesize=${this.pagesize}`;
      } else {
        var url = `users?pagenum=${this.nu}&pagesize=${this.pagesize}&query=` + query;
      }
      this.$axios({
        url,
        method: "get",
        // headers: { Authorization: localStorage.getItem("token") }
      }).then(backdata => {
        console.log(backdata);
        var { data, meta } = backdata.data;
        this.total = data.total;
        this.userData = data.users;
      });
    },

    // 模糊查询
    searchUser() {
      // 获取关键传入getusers
      this.getusers(this.search);
    },

    // 修改用户状态
    mg_change(row) {
      // 获取传入的用户信息，得到id及已改过的状态
      //
      // console.log(row)
      // console.log(state);
      // alert(1);

      this.$axios({
        // 使用es6模块字符语法拼装url路径
        url: `users/${row.id}/state/${row.mg_state}`,
        method: "put",
        // headers: { Authorization: localStorage.getItem("token") }
      }).then(backdata => {
        // console.log(backdata);
        var { data, meta } = backdata.data;
        if (meta.status === 200) {
          this.$message({ message: meta.msg, type: "success" });
        } else {
          this.$message.error(meta.msg);
        }
      });
    },

    // 删除用户
    delUser(id) {
      // el-ui 提供确认弹窗
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          //   发送删除请求
          this.$axios({
            url: "users/" + id,
            method: "delete",
            // headers: { Authorization: localStorage.getItem("token") }
          }).then(backdata => {
            var { data, meta } = backdata.data;
            if (meta.status == 200) {
              this.$message({ message: meta.msg, type: "success" });
              // 更新数据
              this.getusers();
            } else {
              this.$message.error(meta.msg);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },

    // 添加用户
    addUserPost() {
      // this.addUser
      this.$axios({
        url: "users",
        method: "post",
        data: this.addUser,
        // headers: { Authorization: localStorage.getItem("token") }
      }).then(backdata => {
        // console.log(backdata);
        var { data, meta } = backdata.data;
        if (meta.status == 201) {
          this.isShowAddUser = false; //关窗口
          this.$message({ message: meta.msg, type: "success" });
          this.getusers();
        }
      });
    },

    // 修改用户窗口
    editUser(userdata) {
      this.editUserData = userdata;
      this.isShowEditUser = true;
    },

    // 修改用户信息 发送请求
    editUserPut() {
      //  console.log(this.editUserData);
      this.$axios({
        url: "users/" + this.editUserData.id,
        method: "put",
        data: {
          email: this.editUserData.email,
          mobile: this.editUserData.mobile
        },
        // headers: { Authorization: localStorage.getItem("token") }
      }).then(backdata => {
        // console.log(backdata);
        var { data, meta } = backdata.data;
        if (meta.status == 200) {
          this.$message({ message: meta.msg, type: "success" });
          this.isShowEditUser = false;
        } else {
          this.$message.error(meta.msg);
        }
      });
    },

    // 分配用户角色弹窗
    editRole(userdata) {
      this.editRoleData = userdata;
      this.$axios({
        url: "roles",
        method: "get",
        // headers: { Authorization: localStorage.getItem("token") }
      }).then(backdata => {
        // console.log(backdata);
        this.options = backdata.data.data;
      });
      this.isShowEditRole = true;
    },

    // 发送分配角色数据
    editRolePut() {
      // console.log(this.value);
      this.$axios({
        url:`users/${this.editRoleData.id}/role`,
        method:'put',
        data:{rid:this.value},
        // headers: { Authorization: localStorage.getItem("token") }
      }).then(backdata=>{
        // console.log(backdata);
        var {data,meta} = backdata.data;
        if(meta.status == 200){
          this.isShowEditRole = false;
          this.$message({message:meta.msg,type:'success'});
        }else{
          this.$message.error(meta.msg);
        }
      })

    }
  },

  // 页面渲染之前执行的钩子函数，获取数据
  mounted() {
    //  调用getuser方法
    this.getusers();
    // Axios.get('http://tp5.cn/')
    // .then(backdata=>{
    //   // console.log(backdata);
    //   this.userData = backdata.data;
    // })
  }
};
</script>

<style>
.sou {
  line-height: 50px;
}
.has-gutter {
  line-height: 30px;
}
</style>
